import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    users: JSON.parse(localStorage.getItem('users')) || {},
    currentUser: localStorage.getItem('currentUser') || null
  }),
  actions: {
    login(username, password) {
      if (this.users[username] === password) {
        this.currentUser = username;
        localStorage.setItem('currentUser', username);
        return true;
      }
      return false;
    },
    register(username, password) {
      if (!this.users[username]) {
        this.users[username] = password;
        localStorage.setItem('users', JSON.stringify(this.users));
        return true;
      }
      return false;
    },
    signIn() {
      if (!this.currentUser) return false;
      const now = new Date();
      const signInTime = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
      const userRecords = JSON.parse(localStorage.getItem(`signInRecords_${this.currentUser}`)) || [];

      if (userRecords.includes(signInTime)) return false;

      userRecords.push(signInTime);
      localStorage.setItem(`signInRecords_${this.currentUser}`, JSON.stringify(userRecords));
      return true;
    },
    getRecords() {
      if (!this.currentUser) return [];
      return JSON.parse(localStorage.getItem(`signInRecords_${this.currentUser}`)) || [];
    },
    logout() {
      this.currentUser = null;
      localStorage.removeItem('currentUser');
    }
  }
});
